#bin/bash
set -e


echo ">>Step 1: Init project info and verserion "

. ./projectinfo.sh

echo "PROJECT_NAME=$PROJECT_NAME"
echo "DOCKER_IMAGETAG=$DOCKER_IMAGETAG"
echo "DOCKER_VERSION=$DOCKER_VERSION"
echo ""

export DOCKER_USERNAME="janl"
export DOCKER_PASSWORD="uj81u1"

#export IMAGE_HOST="110.249.183.182:10002"
export IMAGE_HOST="192.168.1.144:5000"
export DOCKER_RESPOSTORY="http://$IMAGE_HOST"

echo ">>Step 2: Check docker config file daemon.json"

if [ ! -f "/etc/docker/daemon.json" ] ;then

    echo 'create user config file: /etc/docker/daemon.json:
        {
            "insecure-registries": ["110.249.183.182:10002"],
            "dns":["202.99.160.68"]
        }
    ' 
else
    echo "You /ect/docker/daemon.json file is exist."

fi

#docker logout
docker logout

echo ""

echo ">>Setp 3: Clean builded images..."


echo "clean none images:"
export NID
export NINAME
export NNAME="<none>"
docker images | awk ' { print $1,$3 }' | while read NINAME NID; do
    #echo "NNAME:$NNAME, NINAME:$NINAME"
    if [[ "$NINAME" = "$NNAME" ]];then
        echo "Do remove image:$NINAME"
        echo "Do remove imageid:$NID"
        docker rmi -f $NID
    fi 
done


#export CONTAINERS=$(docker ps -a | awk ' index($2,$DOCKER_IMAGETAG) > 0 { print $1 }')
#echo $CONTAINERS
echo "clean containers:"
export CID
export CINAME
docker ps -a | awk ' { print $1,$2 }' | while read CID CINAME; do
    #echo "CINAME:$CINAME,DOCKER_IMAGETAG:$DOCKER_IMAGETAG"
    if [[ "$CINAME" = "$DOCKER_IMAGETAG" ]];then
        echo "Do remove container:$CINAME"
        docker stop $CID
        docker rm $CID
    fi 
done

echo ""
echo "clean images:"
export IID
export IINAME
docker images | awk ' { print $1,$3 }' | while read IINAME IID; do
    #echo "IINAME:$IINAME,DOCKER_IMAGETAG:$DOCKER_IMAGETAG"
    if [[ "$IINAME" = "$DOCKER_IMAGETAG" ]] ;then
        echo "Do remove image:$IINAME"
        docker rmi -f $IID
    fi 
done

echo ">>Setp 4: Rebuid images..."

. ./build.sh

echo ">>Setp 5: Do login docker repository...."

echo "$DOCKER_PASSWORD" | docker login -u "$DOCKER_USERNAME" "$DOCKER_RESPOSTORY" --password-stdin


echo ">>Setp 6: Do push image to repostory...."
docker tag $DOCKER_IMAGETAG:$DOCKER_VERSION $IMAGE_HOST/$DOCKER_IMAGETAG:$DOCKER_VERSION
docker push $IMAGE_HOST/$DOCKER_IMAGETAG:$DOCKER_VERSION
